package io.renren.membermanage.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import cn.hutool.core.util.ObjectUtil;
import io.renren.util.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import io.renren.membermanage.service.DownloadFileService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/download")
@Tag(name = "文件下载的相关Api")
public class DownloadFileController {

    @Value("${image.sava.path}")
    private String imageSavePath;

    @Autowired
    private DownloadFileService downloadFileService;

    @GetMapping("/downloadZip")
    @Operation(summary = "将指定图片打包成zip并下载", description = "将指定图片打包成zip并下载")
    public void downloadZip(@RequestParam  List<String> images, HttpServletResponse response) throws IOException {
        if (ObjectUtil.isNotEmpty(images)) {
            List<Path> filePaths = new ArrayList<>();
            String workDic = System.getProperty("user.dir");
            workDic = workDic.substring(0,workDic.length()-1);
            workDic = workDic.substring(0,workDic.lastIndexOf("\\"));
            for (String image : images) {
                String imagePath = workDic+imageSavePath + image;
                Path filePath = Paths.get(imagePath).toAbsolutePath().normalize();
                if (Files.exists(filePath) && Files.isRegularFile(filePath)) {
                    filePaths.add(filePath);
                } else {
                    throw new IOException("File not found: " + imagePath);
                }
            }
            downloadFileService.zipFilesAndDownload(filePaths, response);
        }
    }

    @GetMapping("/downloadFile")
    @Operation(summary = "指定文件下载", description = "指定文件下载")
    public ResponseEntity<Resource> downloadFile(@RequestParam String image) {
        if (ObjectUtil.isNotNull(image)) {
            try {
                File file = new File(imageSavePath + image);
                // 检查文件是否存在以及是否可读
                if (!file.exists() || !file.isFile() || !file.canRead()) {
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
                }
                Resource resource = new FileSystemResource(file);
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");
                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE); // 或者根据文件类型设置适当的MediaType
                return ResponseEntity.ok()
                        .headers(headers)
                        .contentLength(file.length())
                        .body(resource);
            } catch (Exception ex) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            }
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    //@SaCheckLogin
    @PostMapping("/uploadFiles")
    public ApiResult<String> uploadFolders(@RequestParam("files") List<MultipartFile> files, @RequestParam("userId") Long userId) {
        try {
            Map<String, String> result = downloadFileService.uploadFiles(files, userId);
            if (result.containsKey("uploadDir")) {
                return ApiResult.success(result.get("uploadDir"));
            } else {
                StringBuilder reason = new StringBuilder();
                result.forEach((k, v) -> reason.append(k).append(" ").append(v).append(";").append(" "));
                return ApiResult.fail(reason.toString());
            }
        } catch (IOException e) {
            return ApiResult.fail("文件上传失败");
        }
    }
}
